<template>
  <div class="login-container">
    <el-card class="login-card" style="width: 460px;">
      <el-form-item>
        <!-- 绑定点击事件来切换头像 -->
        <el-avatar :size="60" :src="avatarUrl" @click="triggerAvatarUpload" style="margin-left: 41%;"></el-avatar>
        <!-- 文件输入用于上传头像 -->
        <input type="file" @change="handleAvatarUpload" ref="avatarInput" style="display: none;">
      </el-form-item>
      <el-form :model="loginForm" label-position="top">
        <el-form-item label="用户名" style="width: 414px;">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" show-password style="width: 414px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitLogin" style="margin-left: 40%;">登录</el-button>
          <el-button type="text" @click="goToRegister" style="margin-left: 20px; color: #999999;">注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElCard, ElForm, ElFormItem, ElInput, ElButton, ElAvatar, ElMessage } from 'element-plus';

const router = useRouter();

function goToRegister() {
  router.push({ name: 'Register' });
}

// 响应式数据
const loginForm = reactive({
  username: '',
  password: ''
});

// 头像列表
const avatars = ref([
  'https://via.placeholder.com/150',
  'https://via.placeholder.com/150?text=B',
  'https://via.placeholder.com/150?text=C'
]);

// 当前头像 URL
const avatarUrl = ref(avatars.value[0]);

// 文件输入引用
const avatarInput = ref(null);


// 触发头像上传
const triggerAvatarUpload = () => {
  avatarInput.value.click();
};

// 处理头像上传
const handleAvatarUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      avatarUrl.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};

// 提交登录
const submitLogin = () => {
  if (loginForm.username === '陈莎莎' && loginForm.password === '123456') {
    router.push('/home/index');
    ElMessage({
      message: '登录成功',
      type: 'success',
    });
    // 模拟登录成功，清空表单
    loginForm.username = '';
    loginForm.password = '';
  }else{
    ElMessage.error('用户名或密码错误');
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-card {
  width: 100%;
  max-width: 600px;
}
</style>